const express = require('express');
const socketio = require('socket.io');
const http = require('http');
const path = require('path');
const { getRoomUsers, userLeave, userJoin } = require('./user');



//需要先把服务启动起来 npm run dev   
const app = express();
const server = http.createServer(app);
const io = socketio(server);



//on 听  emit 讲 监听服务器是否连接 并向前端发送数据
io.on("connection", (socket) => {
    socket.on("joinRoom", ({ name, room }) => {
        socket.join(room);


        //只给房间内的人们发送消息
        userJoin(socket.id, name, room);
        io.to(room).emit("roomUsers", getRoomUsers(room));

        socket.to(room).emit("sysMessage", "欢迎" + name + "加入聊天室");
        socket.on("chatMessage", message => {
            //将接收到的数据传递给前端 实现了实时沟通
            //io 在全局上把消息推给所有人
            io.to(room).emit("chatMessage", message);
        });

        socket.on("disconnect", () => {
            userLeave(socket.id);

            io.to(room).emit("roomUsers", getRoomUsers(room));
        })
    })

})




app.use(express.static(path.join(__dirname, 'public')));




//端口号
const PORT = process.env.PORT || 9527;

//开启服务
server.listen(PORT, () => {
    console.log("This server is running on port" + PORT);
})